import router from "@/router/index.ts";
import { RouteLocationNormalized, NavigationGuardNext } from "vue-router";
import { showNprogress, hiddenNprogress } from "@/utils/index.ts";
import { koiMsgWarning } from "@/utils/koi.ts";
// import { koiSessionStorage } from "@/utils/storage";
import useUserStore from "@/store/user/index.ts";

// 全局守卫：项目当中任意路由切换都会触发的钩子
// 全局前置守卫
// @ts-nocheck
router.beforeEach(
  (
    to: RouteLocationNormalized,
    from: RouteLocationNormalized,
    next: NavigationGuardNext,
  ) => {
    // to：你将要访问哪个路由，from: 你从哪个路由来，next: 路由放行
    console.log("前置守卫", to, from);
    const userStore = useUserStore();
    // const isLogin = koiSessionStorage.get("user");
    // 开启全屏动画
    showNprogress();
    console.log("isLogin", userStore.getToken);
    if (userStore.getToken) {
      // 处理keep-alive三级页面不缓存
      // if (to.matched && to.matched.length > 2) {
      //   to.matched.splice(1,to.matched.length -2 )
      //   next()
      // }
      // 用户token存在
      // console.log("路由菜单",JSON.stringify(routeStore.getDynamicRoutes));
      // 登录成功，访问login，拒绝访问，指向首页
      if (to.path == "/login" || to.path == "/") {
        next({ path: "/home" });
      } else {
        next();
      }
    } else {
      // 用户未登录
      if (to.path == "/login") {
        next();
      } else {
        koiMsgWarning("账号身份已过期，请重新登录🌻");
        next({ path: "/login", query: { redirect: to.path } });
      }
    }
  },
);

// 全局后置守卫
router.afterEach(
  (to: RouteLocationNormalized, from: RouteLocationNormalized) => {
    console.log("后置守卫", to, from);
    // 开启全屏动画
    // 结束全屏动画
    hiddenNprogress();
    // 标题切换
    document.title = to.meta.title + "🌻" || "YU-ADMIN🌻";
  },
);
